/**
  ******************************************************************************
  * @file    IAP_Main/Src/common.c
  * @author  MCD Application Team
  * @version V1.6.0
  * @date    12-May-2017
  * @brief   This file provides all the common functions.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */

/** @addtogroup STM32F1xx_IAP_Main
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "common.h"
#include "usart.h"
#include "ymodem.h"
#include "flash_if.h"
#include "flash_if.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
// uint8_t aFileName[FILE_NAME_LENGTH];
extern uint8_t aFileName[FILE_NAME_LENGTH];
/**
  * @brief  Convert an Integer to a string
  * @param  p_str: The string output pointer
  * @param  intnum: The integer to be converted
  * @retval None
  */
void Int2Str(uint8_t *p_str, uint32_t intnum) {
    uint32_t i, divider = 1000000000, pos = 0, status = 0;

    for (i = 0; i < 10; i++) {
        p_str[pos++] = (intnum / divider) + 48;

        intnum = intnum % divider;
        divider /= 10;
        if ((p_str[pos - 1] == '0') & (status == 0)) {
            pos = 0;
        } else {
            status++;
        }
    }
}

/**
  * @brief  Convert a string to an integer
  * @param  p_inputstr: The string to be converted
  * @param  p_intnum: The integer value
  * @retval 1: Correct
  *         0: Error
  */
uint32_t Str2Int(uint8_t *p_inputstr, uint32_t *p_intnum) {
    uint32_t i = 0, res = 0;
    uint32_t val = 0;

    if ((p_inputstr[0] == '0') && ((p_inputstr[1] == 'x') || (p_inputstr[1] == 'X'))) {
        i = 2;
        while ( ( i < 11 ) && ( p_inputstr[i] != '\0' ) ) {
            if (ISVALIDHEX(p_inputstr[i])) {
                val = (val << 4) + CONVERTHEX(p_inputstr[i]);
            } else {
                /* Return 0, Invalid input */
                res = 0;
                break;
            }
            i++;
        }

        /* valid result */
        if (p_inputstr[i] == '\0') {
            *p_intnum = val;
            res = 1;
        }
    } else { /* max 10-digit decimal input */
        while ( ( i < 11 ) && ( res != 1 ) ) {
            if (p_inputstr[i] == '\0') {
                *p_intnum = val;
                /* return 1 */
                res = 1;
            } else if (((p_inputstr[i] == 'k') || (p_inputstr[i] == 'K')) && (i > 0)) {
                val = val << 10;
                *p_intnum = val;
                res = 1;
            } else if (((p_inputstr[i] == 'm') || (p_inputstr[i] == 'M')) && (i > 0)) {
                val = val << 20;
                *p_intnum = val;
                res = 1;
            } else if (ISVALIDDEC(p_inputstr[i])) {
                val = val * 10 + CONVERTDEC(p_inputstr[i]);
            } else {
                /* return 0, Invalid input */
                res = 0;
                break;
            }
            i++;
        }
    }

    return res;
}

/**
  * @brief  Print a string on the HyperTerminal
  * @param  p_string: The string to be printed
  * @retval None
  */
void Serial_PutString(uint8_t *p_string) {
    uint16_t length = 0;

    while (p_string[length] != '\0') {
        length++;
    }
    HAL_UART_Transmit(&huart1, p_string, length, TX_TIMEOUT);
}

/**
  * @brief  Transmit a byte to the HyperTerminal
  * @param  param The byte to be sent
  * @retval HAL_StatusTypeDef HAL_OK if OK
  */
HAL_StatusTypeDef Serial_PutByte( uint8_t param ) {
    return HAL_UART_Transmit(&huart1, &param, 1, TX_TIMEOUT);
}

uint32_t Set_Upgrade_Flag(uint32_t Flag)
{
	if (FLASHIF_OK == FLASH_If_Erase(LAST_PAGE_START_ADDRESS, FLASH_PAGE_SIZE))
	{
		if (FLASHIF_OK == FLASH_If_Write(LAST_PAGE_START_ADDRESS, &Flag, sizeof(Flag)/sizeof(uint32_t)))
		{
			return RET_OK;
		}
	}
	return RET_ERR;
}
/**
  * @brief  Download a file via serial port
  * @param  None
  * @retval None
  */
void SerialDownload(void) {
    uint8_t number[11] = {0};
    uint32_t size = 0;
    COM_StatusTypeDef result;
    uint32_t upgflg = SET_UPGRADE_FLAG;

    Serial_PutString((uint8_t *)"Waiting for the file to be sent ... (press 'a' to abort)\n\r");
    result = Ymodem_Receive( &size );
    if (result == COM_OK) {
    	if (RET_OK == Set_Upgrade_Flag(upgflg))
    	{
            Serial_PutString((uint8_t *)"\n\n\r Programming Completed Successfully!\n\r--------------------------------\r\n Name: ");
            Serial_PutString(aFileName);
            Int2Str(number, size);
            Serial_PutString((uint8_t *)"\n\r Size: ");
            Serial_PutString(number);
            Serial_PutString((uint8_t *)" Bytes\r\n");
            Serial_PutString((uint8_t *)"-------------------\n");
    	}
    	else
    	{
    		Serial_PutString((uint8_t *)"\n\n\rSet upgrade flag failed!\n\r");
    	}
    } else if (result == COM_LIMIT) {
        Serial_PutString((uint8_t *)"\n\n\rThe image size is higher than the allowed space memory!\n\r");
    } else if (result == COM_DATA) {
        Serial_PutString((uint8_t *)"\n\n\rVerification failed!\n\r");
    } else if (result == COM_ABORT) {
        Serial_PutString((uint8_t *)"\r\n\nAborted by user.\n\r");
    } else {
        Serial_PutString((uint8_t *)"\n\rFailed to receive the file!\n\r");
    }
}

/**
  * @brief  Upload a file via serial port.
  * @param  None
  * @retval None
  */
void SerialUpload(void) {
    uint8_t status = 0;

    Serial_PutString((uint8_t *)"\n\n\rSelect Receive File\n\r");

    HAL_UART_Receive(&huart1, &status, 1, RX_TIMEOUT);
    if ( status == CRC16) {
        /* Transmit the flash image through ymodem protocol */
        status = Ymodem_Transmit((uint8_t*)APPLICATION_ADDRESS, (const uint8_t*)"UploadedFlashImage.bin", USER_FLASH_SIZE);

        if (status != 0) {
            Serial_PutString((uint8_t *)"\n\rError Occurred while Transmitting File\n\r");
        } else {
            Serial_PutString((uint8_t *)"\n\rFile uploaded successfully \n\r");
        }
    }
}

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
